// eslint-disable-next-line no-undef
const {contextBridge, ipcRenderer} = require('electron')
// eslint-disable-next-line no-undef
const mysql = require('mysql')


const operationSet = {
    ">": (field, value) => `${field} > ${value}`,
    ">=": (field, value) => `${field} >= ${value}`,
    "<=": (field, value) => `${field} <= ${value}`,
    "<": (field, value) => `${field} < ${value}`,
    "=": (field, value) => (typeof value) === "string" ? `${field} = '${value}'` : `${field} = ${value}`,
    "!=": (field, value) => (typeof value) === "string" ? `${field} != '${value}'` : `${field} != ${value}`,
    "like": (field, value) => `${field} like '%${value}%'`,
    "in": (field, value) => `${field} in (${value.join(',')})`,
    "between": (field, value) => `${field} between ${value[0]} and ${value[1]}`,
}


const getOffsetByPagination = (pagination) => {
    return ` LIMIT ${pagination.pageSize} OFFSET ${(pagination.page - 1) * pagination.pageSize} `
}
const getWhereByFilters = (filters) => {
    if (!filters.length) return '';
    let result = "where "
    filters?.forEach((filter, index) => {
        if (index) result += " and "
        result += operationSet[filter.operation](filter.field, filter.value)
    })
    return result
}

const getItemsCount = (filters, callback) => {
    // 创建数据库连接池，配置基本信息，连接mysql

    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        port: '3735',
        database: 'legion_cms'
    });
    let sql = "select count(a.ID) as total from item a left join item_sparse b on a.id = b.id "
    sql += getWhereByFilters(filters)
    connection.query(sql, null, (err, results) => {
        if (err) throw err;
        callback(results[0])

    })
    connection.end()
}

const queryItems = (filters, pagination, callback) => {
    // 创建数据库连接池，配置基本信息，连接mysql
    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        port: '3735',
        database: 'legion_cms'
    });
    let sql = `
    select a.ID,
       b.Display,
       b.ItemLevel,
       b.RequiredLevel,
       a.ClassID,
       a.SubclassID,
       a.InventoryType,
       b.OverallQualityID
    from item a
       left join item_sparse b on a.id = b.id 

    `
    sql += getWhereByFilters(filters)
    sql += getOffsetByPagination(pagination)
    connection.query(sql, null, (err, results) => {
        if (err) {
            callback({status: 'err', data: []})
            throw err
        }
        callback({status: 'ok', data: results})
    })
    connection.end()
}

const updateArtifactPower = (role, callback) => {
    // 创建数据库连接池，配置基本信息，连接mysql
    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        port: '3735',
        database: 'legion_cms'
    });
    let sql = `
update legion_characters.item_instance_artifact a
    left join legion_characters.characters b on a.char_guid = b.guid
set a.xp = 9999999999999999
where b.name = "${role}"
    `
    connection.query(sql, null, (err, results) => {
        if (err) {
            callback({status: 'err', data: []})
            throw err
        }
        callback({status: 'ok', data: results})
    })
    connection.end()
}

window.addEventListener('DOMContentLoaded', function () {
    console.log('Preload is Completed !')
})

contextBridge.exposeInMainWorld('electronAPI', {
    min: () => ipcRenderer.send('window-min'),
    close: () => ipcRenderer.send('window-close'),
    queryItems,
    getItemsCount,
    updateArtifactPower
})